<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils\ResponseFactory;
use App\Http\Requests\admin\Group\AddGroupPermissionRequest;
use App\Http\Requests\admin\Group\AddGroupRequest;
use App\Http\Requests\admin\Group\AddUserRequest;
use App\Http\Requests\admin\Group\RemoveUserRequest;
use App\Http\Requests\admin\Group\SelectGroupPermissionRequest;
use App\Http\Requests\admin\Group\SelectGroupUsersRequest;
use App\Http\Requests\admin\Group\SelectUserGroupsRequest;
use App\Http\Requests\admin\Group\UpdateGroupRequest;
use App\Models\Manager\Group;
use App\Models\Manager\GroupManager;
use App\Models\Manager\GroupPermissionRelation;
use App\Models\Manager\GroupUserRelation;
use App\Models\Manager\Permission;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

/**
 *
 */
class GroupController extends Controller
{
    //
    /**添加组
     * @param AddGroupRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addGroup(AddGroupRequest $request): \Illuminate\Http\JsonResponse
    {

        if (Group::all()->where('name', $request->input('name'))->count() > 0) {
            return ResponseFactory::simpleResponse(false, "该组已被添加");
        } else {
            $result = Group::create($request->all('name', 'description'));
            return ResponseFactory::simpleResponse(!($result === null), $result === null ? "添加失败" : "添加成功");
        }
    }

    /**删除组
     * @param int $id groupId
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeGroup(int $id): \Illuminate\Http\JsonResponse
    {
        $userId = auth()->user()->id;
        $groupManager = GroupManager::all()->where('userId', $userId);
        if ($userId === 1 || (is_null($groupManager) && $groupManager->first()->groupId === $id)) {
            $group = Group::find($id);
            if ($group != null) {
                $result = Group::destroy($id);
                if ($result > 0) {
                    return ResponseFactory::simpleResponse(true, "删除成功");
                } else {
                    return ResponseFactory::simpleResponse(false, "删除失败");
                }
            } else {
                return ResponseFactory::simpleResponse(false, "没有要查询到的组");
            }
        }
        return ResponseFactory::simpleResponse(false, "you don't have permission to operate other resource", 401);
    }

    /** 更新组
     * @param UpdateGroupRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateGroup(UpdateGroupRequest $request): \Illuminate\Http\JsonResponse
    {
        if ($request->has('id')) {
            if (Group::find($request->input('id'))) {
                $groupManager = GroupManager::all()->where('groupId', $request->input('id'))->first();
                if (auth()->user()->id === 1 || ($groupManager->roleId === 1 && $groupManager->userId === auth()->user()->id)) {
                    $group = Group::find($request->input('id'));
                    $group->update($request->all());
                    $result = $group->save();
                    return ResponseFactory::simpleResponse($result);
                }
                return ResponseFactory::simpleResponse(false, "you don't have permission to operate other resource", 401);
            }
            return ResponseFactory::simpleResponse(false, "id不存在");
        }
        return ResponseFactory::simpleResponse(false, "缺少id参数");
    }

    /** 查询所有组
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function selectGroup(Request $request): \Illuminate\Http\JsonResponse
    {
        $params = $request->all('pageNum', 'pageSize');
        $rows = Group::all()->forPage($params['pageNum'], $params['pageSize'])->all();
        return ResponseFactory::response(null, $rows);
    }

    /**查询用户所在的组
     * @return \Illuminate\Http\JsonResponse
     */
    public function selectUserGroups(SelectUserGroupsRequest $request): \Illuminate\Http\JsonResponse
    {
        $userId = $request->input('userId');
        $user = User::find($userId);
        if ($user === null) {
            return ResponseFactory::simpleResponse(false, "userId不存在");
        }
        $groups = $user->Group()->get();
        return ResponseFactory::responseRows($groups);
    }

    /** 查询组中所有的用户
     * @param SelectGroupUsersRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function selectGroupUsers(SelectGroupUsersRequest $request): \Illuminate\Http\JsonResponse
    {
        $groupId = $request->input('groupId');
        $group = Group::find($groupId);
        if ($group === null) {
            return ResponseFactory::simpleResponse(false, "groupId is not exit");
        }
        $users = $group->User()->get();
        return ResponseFactory::responseRows($users);
    }


    /**删除组
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function disableGroup(int $id): \Illuminate\Http\JsonResponse
    {
        $group = Group::find($id);
        if ($group != null) {
            $groupManager = GroupManager::all()->where('groupId', $id)->first();
            if (auth()->user()->id === 1 || ($groupManager->roleId === Config::get('normalconfig.group.managerrole.creater') && $groupManager->userId === auth()->user()->id)) {
                if ($group->state) {
                    $group->state = false;
                    if ($group->save() > 0) {
                        return ResponseFactory::simpleResponse(true, "禁用成功");
                    }
                    return ResponseFactory::simpleResponse(false, "禁用失败");
                }
                return ResponseFactory::simpleResponse(false, "该组已被禁用");
            }
            return ResponseFactory::simpleResponse(false, "you don't have permission to operate other resource", 401);
        }
        return ResponseFactory::simpleResponse(false, "没有要查询到的组");
    }

    //未解决重复添加的问题

    /** 为组添加用户
     * @param AddUserRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function AddUser(AddUserRequest $request)
    {
        $datas = $request->input('datas');
        $successCount = 0;
        $repeatCount = 0;
        foreach ($datas as $value) {
            if (auth()->user()->id === Config::get('normalconfig.user.rootId')){
                break;
            }
            $GroupManagerRelation = GroupManager::all()->where('userId', auth()->user()->id)->where('groupId', $value['groupId'])->first();
            if (is_null($GroupManagerRelation) || ($GroupManagerRelation->count() <= 0 &&
                    ($GroupManagerRelation['roleId'] !== Config::get('normalconfig.group.managerrole.creater') ||
                        $GroupManagerRelation['roleId'] !== Config::get('normalconfig.group.managerrole.manager')))) {
                return ResponseFactory::simpleResponse(false, "you don't have permission to add users in other group");
            }
        }

        foreach ($datas as $value) {
            if (GroupUserRelation::all()->where('userId', $value['userId'])->where('groupId', $value['groupId'])->count() === 0) {
                $relation = new GroupUserRelation();
                $relation->userId = $value['userId'];
                $relation->groupId = $value['groupId'];
                $res = $relation->save();
                if (!$res) {
                    return ResponseFactory::simpleResponse(false, "添加失败");
                }
                $successCount++;
            } else {
                $repeatCount++;
            }
        }
        $data['success'] = $successCount;
        $data['repeat'] = $repeatCount;
        return ResponseFactory::customResponse([
            'data' => $data
        ]);
    }

    /**为组删除用户
     * @param RemoveUserRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeUser(RemoveUserRequest $request)
    {
        $datas = $request->input('datas');
        $successCount = 0;
        $error = 0;
        foreach ($datas as $value) {
            if (auth()->user()->id === Config::get('normalconfig.user.rootId')){
                break;
            }
            $GroupManagerRelation = GroupManager::all()->where('userId', auth()->user()->id)->where('groupId', $value['groupId'])->first();
            if (is_null($GroupManagerRelation) || ($GroupManagerRelation->count() <= 0 &&
                    ($GroupManagerRelation['roleId'] !== Config::get('normalconfig.group.managerrole.creater') ||
                        $GroupManagerRelation['roleId'] !== Config::get('normalconfig.group.managerrole.manager')))) {
                return ResponseFactory::simpleResponse(false, "you don't have permission to add users in other group");
            }
        }

        foreach ($datas as $item) {
            $relation = GroupUserRelation::all()->where('userId', $item['userId'])->where('groupId', $item['groupId'])->first();
            if (!is_null($relation)) {
                $result = GroupUserRelation::destroy($relation['id']);
                if ($result <= 0) {
                    return ResponseFactory::simpleResponse(false, "删除失败");
                }
                $successCount++;
            } else {
                $error++;
            }
        }
        $data['success'] = $successCount;
        $data['error'] = $error;
        return ResponseFactory::customResponse([
            'data' => $data
        ]);
    }

    /** 设置组的权限
     * @return \Illuminate\Http\JsonResponse
     */
    public function SetGroupPermission(AddGroupPermissionRequest $request): \Illuminate\Http\JsonResponse
    {
        $datas = $request->all('permissions');
        foreach ($datas['permissions'] as $key => $value) {
            if (Group::find($value['groupId']) === null) {
                return ResponseFactory::simpleResponse(false, "The groupId is not exit in Index is {$key}");
            }
            if (Permission::find($value['permissionId']) === null) {
                return ResponseFactory::simpleResponse(false, "The groupId is not exit in Index is {$key}");
            }
            if (GroupPermissionRelation::all()->where('groupId', $value['groupId'])->where('permissionId', $value['permissionId'])->count() > 0) {
                return ResponseFactory::simpleResponse(false, "The item is exit where index is {$key}");
            }
        }
        $result = DB::table('group_permission_relation')->insert((array)$datas['permissions']);
        return ResponseFactory::simpleResponse($result, $result ? "设置成功" : "设置失败");

    }

    /** 删除组的权限
     * @return \Illuminate\Http\JsonResponse
     */
    public function RemoveGroupPermission(int $id)
    {
        if (GroupPermissionRelation::find($id) === null) {
            return ResponseFactory::simpleResponse(false, "id不存在");
        }
        $result = GroupPermissionRelation::destroy($id);
        return ResponseFactory::simpleResponse($result > 0, $result > 0 ? "操作成功" : "操作失败");
    }


    /**禁用组
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function disableGroupPermission(int $id)
    {
        $relation = GroupPermissionRelation::find($id);
        if ($relation === null) {
            return ResponseFactory::simpleResponse(false, "id不存在");
        }
        if (!$relation->state) {
            return ResponseFactory::simpleResponse(false, '此项权限已被禁用');
        }
        $relation->state = false;
        $result = $relation->save();
        return ResponseFactory::simpleResponse($result, $result ? "禁用成功" : "禁用失败");
    }

    /** 查询组的权限
     * @return \Illuminate\Http\JsonResponse
     */
    public function SelectGroupPermission(SelectGroupPermissionRequest $request)
    {
        $groupId = $request->input('groupId');
        $group = Group::find($groupId);
        if ($group === null) {
            return ResponseFactory::simpleResponse(false, "groupId 不存在", 404);
        }
        $rows = $group->Permission()->get();
        return ResponseFactory::customResponse([
            'rows' => $rows,
            'count' => count($rows)
        ]);
    }


}
